/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AtivacaoDialog.java
 *
 * Created on Nov 24, 2011, 11:37:39 PM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControlePedido;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.gui.table.AtivacaoEntrantesTableModel;
import br.com.tbp.gui.table.JTableUtils;
import br.com.tbp.model.domain.ItemDePedido;
import br.com.tbp.utils.ImageUtils;
import java.awt.Component;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.SpinnerDateModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;

/**
 *
 * @author Diego
 */
public class AtivacaoEntrantesFrame extends javax.swing.JFrame {

    private AtivacaoEntrantesTableModel tableModel;
    private ControlePedido controle = new ControlePedido();
    private List<ItemDePedido> itensList;

    public AtivacaoEntrantesFrame(String title) {
        super(title);
        initComponents();
        setIconImage(ImageUtils.createIcon("sistema.png").getImage());
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        d1 = new org.jdesktop.swingx.JXDatePicker();
        d2 = new org.jdesktop.swingx.JXDatePicker();
        okButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        pesquisarButton = new javax.swing.JButton();
        qtdeLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        table.setSelectionBackground(new java.awt.Color(121, 177, 231));
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(table);

        jLabel1.setText("Data do pedido entre:");

        okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/accept.png"))); // NOI18N
        okButton.setText("OK");
        okButton.setToolTipText("Salvar modificações");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        pesquisarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/magnifier.png"))); // NOI18N
        pesquisarButton.setToolTipText("Pesquisar entrantes...");
        pesquisarButton.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        pesquisarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pesquisarButtonActionPerformed(evt);
            }
        });

        qtdeLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        qtdeLabel.setText("0 entradas localizadas");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 1016, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(729, Short.MAX_VALUE)
                .addComponent(qtdeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 992, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(d1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(d2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(12, 12, 12)
                        .addComponent(pesquisarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(701, 701, 701))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(d1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pesquisarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(d2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(qtdeLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(okButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        if (getItensList() == null || getItensList().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Nenhum modificação foi realizada.", "Mensagem do sistema", 2);
        } else {
            try {
                controle.atualizarAtivacoes(getItensList());
                JOptionPane.showMessageDialog(null, "As modificações foram realizadas com sucesso.", "Mensagem do sistema", 1);
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
        dispose();
    }//GEN-LAST:event_okButtonActionPerformed

    private void pesquisarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pesquisarButtonActionPerformed
        findItensAtivados(d1.getDate(), d2.getDate());
    }//GEN-LAST:event_pesquisarButtonActionPerformed

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AtivacaoEntrantesFrame dialog = new AtivacaoEntrantesFrame("TBP - Ativação de Entrantes");
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXDatePicker d1;
    private org.jdesktop.swingx.JXDatePicker d2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton okButton;
    private javax.swing.JButton pesquisarButton;
    private javax.swing.JLabel qtdeLabel;
    private javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables

    private void findItensAtivados(Date _1, Date _2) {
        if (_1 == null || _2 == null) {
            d1.requestFocus();
            return;
        }
        try {
            List<ItemDePedido> itensList = controle.getAtivacoesPelaData(_1, _2);
            setItensList(itensList);
            tableModel = new AtivacaoEntrantesTableModel(itensList);
            table.setModel(tableModel);

            adjustTable();

            if (itensList.size() == 0) {
                qtdeLabel.setText("1 entrada localizada");
            } else {
                qtdeLabel.setText(itensList.size() + " entradas localizadas");
            }
            JTableUtils.fitAllColumnsWithoutRenderer(table);
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    public List<ItemDePedido> getItensList() {
        return itensList;
    }

    public void setItensList(List<ItemDePedido> itensList) {
        this.itensList = itensList;
    }

    private void adjustTable() {
        table.setDefaultRenderer(Date.class, new DateRenderer());
        table.setDefaultEditor(Date.class, new DateCellEditor());
        //table.setDefaultRenderer(Integer.class, new NumberRenderer());
        //table.setDefaultEditor(Date.class, new NumberCellEditor());
    }

    class DateCellEditor extends AbstractCellEditor implements
            TableCellEditor {

        int selectedRow;
        int selectedColumn;
        JTable currentTable;
        Date currentDate;
        JSpinner spinner;
        protected static final String EDIT = "edit";

        public DateCellEditor() {
            Calendar calendar = Calendar.getInstance();
            Date initDate = calendar.getTime();
            calendar.add(Calendar.YEAR, -100);
            Date earliestDate = calendar.getTime();
            calendar.add(Calendar.YEAR, 200);
            Date latestDate = calendar.getTime();
            SpinnerDateModel dateModel = new SpinnerDateModel(initDate, earliestDate,
                    latestDate, Calendar.YEAR);// ignored for user input
            spinner = new JSpinner(dateModel);

            spinner.setEditor(new JSpinner.DateEditor(spinner, "dd/MM/yyyy"));
        }

        public Component getTableCellEditorComponent(JTable table, Object value,
                boolean isSelected, int row, int column) {
            spinner.setValue(value);
            currentTable = table;
            selectedRow = row;
            selectedColumn = column;
            return spinner;
        }

        public Object getCellEditorValue() {
            return spinner.getValue();
        }
    }

    static class DateRenderer extends DefaultTableCellRenderer {

        DateFormat formatter;

        public DateRenderer() {
            super();
        }

        @Override
        public void setValue(Object value) {
            if (formatter == null) {
                formatter = DateFormat.getDateInstance();
            }
            setText((value == null) ? "" : formatter.format(value));
        }
    }
}
